package com.crazypos.security.service;

import com.crazypos.pojo.PermissionEntity;
import com.crazypos.pojo.UserEntity;
import com.crazypos.pojo.UserRoleEntity;
import com.crazypos.pojo.vo.RoleMenuVO;
import com.crazypos.pojo.vo.UserRoleVO;
import com.crazypos.security.entity.UserDetailEntity;
import com.crazypos.service.IRoleService;
import com.crazypos.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserDetailService implements UserDetailsService {

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    @Override
    @Transactional
    public UserDetailEntity loadUserByUsername(String username) throws UsernameNotFoundException {
        UserEntity userEntity = userService.getUserByAccnount(username);
        if (userEntity != null) {
            UserDetailEntity userDetail = new UserDetailEntity();
            BeanUtils.copyProperties(userEntity, userDetail);
            userDetail.setUsername(username);
            UserRoleVO userRoleEntity = roleService.getRoleByUserId(userEntity.getId());

            if(userRoleEntity != null){
                userDetail.setRoleId(userRoleEntity.getRoleId());
                userDetail.setRoleName(userRoleEntity.getRoleName());

                // 查询权限
                List<String> permissions = roleService.getPermissionByRoleId(userRoleEntity.getRoleId(), userDetail.getOrganizationId());
                userDetail.setPermissions(permissions);

                // 查询侧栏菜单
                List<RoleMenuVO> navMenus = roleService.getRoleMenu(userRoleEntity.getRoleId(), 1, userDetail.getOrganizationId());
                userDetail.setNavMenus(navMenus);

                // 查询权限菜单
                List<RoleMenuVO> roleMenus = roleService.getRoleMenu(userRoleEntity.getRoleId(), 2, userDetail.getOrganizationId());
                userDetail.setRoleMenus(roleMenus);
            }else{
                userDetail.setRoleId("-1");
                userDetail.setRoleName("unknown");
                userDetail.setPermissions(new ArrayList<>());
                userDetail.setNavMenus(new ArrayList<>());
                userDetail.setRoleMenus(new ArrayList<>());
            }


            return userDetail;
        }
        return null;
    }
}
